package com.lingfengerick.commons.net;


import com.lingfengerick.commons.constant.Constant;
import com.lingfengerick.commons.constant.NumberConstant;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lingfengerick
 * @since 2021/8/13 11:01 下午
 */
public class IpUtils {


    /**
    *
    * 获取请求的地址,
    * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
    * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
    * @author  lingfengerick
    * @since 2021/8/13  11:14 下午
    * @param httpServletRequest 请求对象
    * @return 请求地址
    *
    */
    public static String getIpAddress(HttpServletRequest httpServletRequest){
        String ipAddress = httpServletRequest.getHeader(Constant.HEADER_X_FORWARDED_FOR);
        if (StringUtils.isEmpty(ipAddress) || Constant.HEADER_UNKNOWN.equalsIgnoreCase(ipAddress)){
            ipAddress = httpServletRequest.getHeader(Constant.HEADER_X_REAL_IP);
        }
        if (StringUtils.isEmpty(ipAddress) || Constant.HEADER_UNKNOWN.equalsIgnoreCase(ipAddress)){
            ipAddress = httpServletRequest.getHeader(Constant.HEADER_PROXY_CLIENT_IP);
        }
        if (StringUtils.isEmpty(ipAddress) || Constant.HEADER_UNKNOWN.equalsIgnoreCase(ipAddress)){
            ipAddress = httpServletRequest.getHeader(Constant.HEADER_WL_PROXY_CLIENT_IP);
        }
        if (StringUtils.isEmpty(ipAddress) || Constant.HEADER_UNKNOWN.equalsIgnoreCase(ipAddress)){
            ipAddress = httpServletRequest.getRemoteAddr();
        }
        /**
        * 使用代理，获取第一个Ip地址
        */
        if (StringUtils.isNoneEmpty(ipAddress) && ipAddress.split(Constant.SPIT_CHAR).length > 0){
            ipAddress = ipAddress.split(Constant.SPIT_CHAR)[NumberConstant.NUM_INT_0];
        }
        return ipAddress;
    }

}
